<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/3/9 0009
 * Time: 14:23
 */

namespace logic\yuding\driver;
use logic\LogicException;


class Hotel
{
	//错误信息提示
	public $msg = array();
	//酒店房间信息集合
	public $roomResult = array();
	//前台提交数据源
	public $data = array();

	//设置数据源
	public function setData( $data ){
		$this->data = $data;
	}

	//设置错误信息
	public function setMsg(){
		$this->msg = [
			'maxnum'        =>  '#date# 当天预订已满',
			'advance_day'   =>  '本产品只能提前15天购买,请重新选择日期',
			'isTrueDate'     =>  '需提前一天预订，当天系统不出票'
		];
	}

	//获取房间信息
	public function getRoom(){
		$this->roomResult = db('hotelroom')->find($this->data['room_id']);
	}

	/** 获取出游日期价格
	 *  moneys 返回房间的价格信息
	 *  discount_vouchers 返回优惠金额
	 **/
	public function price(){
		empty($this->roomResult) && $this->getRoom();
		//特殊日期金额计算
		if(!empty($this->roomResult['special_date'])){
			$day_list=explode(',',$this->roomResult['special_date']);
			foreach($day_list as $key => $dd){
				$days=explode('|',$dd);
				if(strtotime($this->data['date'])==strtotime($days[0])){
					$this->data['moneys'] = $days[1];
				}
			}
		}
		//优惠金额计算
		$this->data['discount_vouchers'] = 0;
		if(intval($this->roomResult['vouchers']) > 0){
			$this->data['discount_vouchers']= $this->data['vouchers'] * $this->roomResult['vouchers_moneys'];
		}
		//计算最终结果
		$this->data['moneys'] = $this->data['moneys'] - $this->data['discount_vouchers'];
	}

	/** 验证当日最大预订量
	 *@param $max			int		//单日最大预订限制数量
	 *@param $yudingdate	string	//出游日期
	 *@param $rid			int 	//房型标识
	 *@return bool
	 **/
	public function dayMaxNum(){
		empty($this->roomResult) && $this->getRoom();
		$cnt = db('wxpay_detail')
			->alias('w')
			->join('order o' , 'w.order_id = o.id')
			->where('o.productId' , $this->data['rid'])
			->where('o.yudingdate' , $this->data['date'])
			->where('w.pay_code' , 'SUCCESS')
			->where('w.refund_code is null')
			->count();
		if($cnt >= $this->roomResult['maxnum']){
			throw new LogicException(str_replace('#date#', $this->data['date'], $this->msg['maxnum']));
		}
	}

	/** 验证出游日期
	 *@param $yudingdate	string	//出游日期
	 *@return bool
	 **/
	public function isTrueDate(){
		empty($this->roomResult) && $this->getRoom();
		if(strtotime($this->data['date'])<=strtotime(date('Y-m-d',time()))){
			throw new LogicException( $this->msg['isTrueDate'] );
		}
		if(strtotime($this->data['date'])>strtotime(date('Y-m-d',strtotime("+ $this->roomResult['advance_day'] day")))){
			throw new LogicException( $this->msg['advance_day'] );
		}
	}

}